const api = require('../../utils/api');
// 从api对象中获取reminderApi
const reminderApi = api.reminder;

Component({
  properties: {
    showReminders: {
      type: Boolean,
      value: true
    }
  },

  data: {
    visible: false,
    reminders: [],
    currentReminder: null,
    currentIndex: 0
  },

  lifetimes: {
    attached() {
      this.checkReminders();
      
      // 设置定时器，每分钟检查一次提醒
      this.checkInterval = setInterval(() => {
        this.checkReminders();
      }, 60000);
    },

    detached() {
      // 清除定时器
      if (this.checkInterval) {
        clearInterval(this.checkInterval);
      }
    }
  },

  methods: {
    async checkReminders() {
      if (!this.properties.showReminders) {
        return;
      }
      
      try {
        // 获取今日提醒
        const result = await reminderApi.getTodayReminders();
        
        // 确保result.data是数组再进行筛选
        if (result && result.success && Array.isArray(result.data)) {
          // 筛选出未完成的提醒并按时间排序
          const pendingReminders = result.data
            .filter(reminder => !reminder.isCompleted)
            .sort((a, b) => {
              const timeA = a.hour * 60 + a.minute;
              const timeB = b.hour * 60 + b.minute;
              return timeA - timeB;
            });
          
          if (pendingReminders.length > 0) {
            this.setData({
              reminders: pendingReminders,
              currentReminder: pendingReminders[0],
              currentIndex: 0,
              visible: true
            });
          } else {
            this.setData({
              visible: false
            });
          }
        } else {
          // 如果不是数组或没有数据，设置空数组
          this.setData({
            reminders: [],
            visible: false
          });
        }
      } catch (error) {
        console.error('检查提醒失败', error);
        // 出错时也设置空数组
        this.setData({
          reminders: [],
          visible: false
        });
      }
    },

    hideAlert() {
      this.setData({
        visible: false
      });
    },

    viewDetails() {
      const reminder = this.data.currentReminder;
      if (reminder) {
        try {
          wx.navigateTo({
            url: `/pages/reminderDetail/reminderDetail?id=${reminder._id}`,
            fail: (err) => {
              console.error('导航到提醒详情页失败', err);
              // 如果导航失败，可能是页面已经打开太多，尝试重定向
              wx.redirectTo({
                url: `/pages/reminderDetail/reminderDetail?id=${reminder._id}`,
                fail: (redirectErr) => {
                  console.error('重定向到提醒详情页也失败', redirectErr);
                  wx.showToast({
                    title: '无法打开提醒详情',
                    icon: 'none'
                  });
                }
              });
            }
          });
        } catch (e) {
          console.error('导航异常', e);
        }
        this.hideAlert();
      }
    },

    async completeReminder() {
      const reminder = this.data.currentReminder;
      if (!reminder) return;
      
      try {
        await reminderApi.completeReminder(reminder._id);
        
        // 更新提醒列表
        const updatedReminders = this.data.reminders.filter(r => r._id !== reminder._id);
        
        if (updatedReminders.length > 0) {
          this.setData({
            reminders: updatedReminders,
            currentReminder: updatedReminders[0],
            currentIndex: 0
          });
        } else {
          this.hideAlert();
        }
        
        wx.showToast({
          title: '已完成提醒',
          icon: 'success'
        });
      } catch (error) {
        console.error('完成提醒失败', error);
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    },

    async snoozeReminder() {
      const reminder = this.data.currentReminder;
      if (!reminder) return;
      
      try {
        // 默认延迟30分钟
        await reminderApi.snoozeReminder(reminder._id, 30);
        
        // 更新提醒列表
        const updatedReminders = this.data.reminders.filter(r => r._id !== reminder._id);
        
        if (updatedReminders.length > 0) {
          this.setData({
            reminders: updatedReminders,
            currentReminder: updatedReminders[0],
            currentIndex: 0
          });
        } else {
          this.hideAlert();
        }
        
        wx.showToast({
          title: '已延迟30分钟',
          icon: 'success'
        });
      } catch (error) {
        console.error('延迟提醒失败', error);
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    },

    nextReminder() {
      const { reminders, currentIndex } = this.data;
      if (reminders.length === 0) return;
      
      const nextIndex = (currentIndex + 1) % reminders.length;
      
      this.setData({
        currentReminder: reminders[nextIndex],
        currentIndex: nextIndex
      });
    },

    prevReminder() {
      const { reminders, currentIndex } = this.data;
      if (reminders.length === 0) return;
      
      const prevIndex = (currentIndex - 1 + reminders.length) % reminders.length;
      
      this.setData({
        currentReminder: reminders[prevIndex],
        currentIndex: prevIndex
      });
    }
  }
}); 